package com.culturalCenter.dataCenter.controller.web;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.culturalCenter.dataCenter.Utils.ApiResult;
import com.culturalCenter.dataCenter.Utils.DoorHttpUtil;
import com.culturalCenter.dataCenter.Utils.LogException;
import com.culturalCenter.dataCenter.Utils.ResultCode;
import com.culturalCenter.dataCenter.customEntity.requestParam.RequestDoorTemplate;
import com.culturalCenter.dataCenter.customEntity.requestParam.RequestVisitorInfo;
import com.culturalCenter.dataCenter.customEntity.responseParam.site.*;
import com.culturalCenter.dataCenter.customEntity.site.CustomSiteBooking;
import com.culturalCenter.dataCenter.customEntity.site.CustomSiteUsedHistory;
import com.culturalCenter.dataCenter.entity.site.SiteAlerts;
import com.culturalCenter.dataCenter.entity.site.SiteUsedCount;
import com.culturalCenter.dataCenter.globalconfig.Interface.ApiVersion;
import com.culturalCenter.dataCenter.globalconfig.Interface.CustomVersion;
import com.culturalCenter.dataCenter.param.DateParam;
import com.culturalCenter.dataCenter.service.site.*;
import com.culturalCenter.dataCenter.vo.SiteUsedDataVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.culturalCenter.dataCenter.Utils.ApiResult.instance;

/**
 * 场地
 *
 * @author ISMC
 * @since 2020/10/17 16:03
 */
@RestController
@RequestMapping("/{version}/site")
@Api(tags = "场地模块")
@ApiVersion(CustomVersion.VERSION_1)
@Slf4j
public class SiteController {

    @Resource
    private SiteService siteService;
    @Resource
    private SiteAlertsService siteAlertsService;
    @Resource
    private SiteBookingService siteBookingService;
    @Resource
    private SiteUsedCountService siteUsedCountService;
    @Resource
    private SiteAlertsMonthService siteAlertsMonthService;
    @Value("${door.key}")
    private String key;
    @Value("${door.empNo}")
    private String empNo;
    @Value("${door.empName}")
    private String empName;
    @Value("${door.dptName}")
    private String dptName;
    @Value("${door.callReason}")
    private String callReason;
    @Value("${door.callerPhoto}")
    private String callerPhoto;
    @Value("${door.callerCarInfo}")
    private String callerCarInfo;
    @Value("${door.callerCorpName}")
    private String callerCorpName;
    @Value("${doorIP}" + "${door.visitorInfoUrl}")
    private String visitorInfoUrl;
    @Value("${doorIP}" + "${door.visitorQrCodeUrl}")
    private String visitorQrCodeUrl;
    @Value("${doorIP}" + "${door.getVisitorInfoUrl}")
    private String getVisitorInfoUrl;

    /**
     * @Description 首页
     * @Param []
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("menu")
    @ApiOperation(value = "场地首页")
    public ApiResult<SiteMenuResponse> getMenu(DateParam param) {
        SiteMenuResponse siteMenuResponse = siteService.getSiteMenu(param);
        return instance(ResultCode.SUCCESS, siteMenuResponse);
    }

    /**
     * @Description 状态
     * @Param []
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("status")
    @ApiOperation(value = "场地状态", notes = "场地状态")
    public ApiResult<SiteStatusResponse> getSiteStatus() {
        SiteStatusResponse siteStatusResponse = siteService.getSiteStatus();
        return instance(ResultCode.SUCCESS, siteStatusResponse);
    }

    /**
     * @Description 查询场地状态
     * @Param []
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("searchStatus")
    @ApiOperation(value = "场地状态", notes = "场地状态")
    public ApiResult<SiteStatusResponse> searchSiteStatus(String start,String end) throws ParseException {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = sdf.parse(start);
        Date endTime = sdf.parse(end);
        int result = startTime.compareTo(new Date());
        if(result==1){
            SiteStatusResponse siteStatusResponse = siteService.searchSiteStatusAfter(startTime,endTime);
//            siteStatusResponse.setTiming(result);
            return instance(ResultCode.SUCCESS, siteStatusResponse);
        }
        SiteStatusResponse siteStatusResponse = siteService.searchSiteStatus(startTime,endTime);
//        siteStatusResponse.setTiming(result);
        return instance(ResultCode.SUCCESS, siteStatusResponse);
    }

    /**
     * @Description 使用率
     * @Param [date]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("usageRate")
    @ApiOperation(value = "场地使用率", notes = "场地使用率")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "年月", paramType = "query", dataType = "Date"),
            @ApiImplicitParam(name = "year", value = "年", paramType = "query", dataType = "Date"),
            @ApiImplicitParam(name = "near", value = "近七天", paramType = "query", dataType = "String")
    })
    public ApiResult<UsedRateResponse> getUsageRateYear(@DateTimeFormat(pattern = "yyyy-MM") @RequestParam(required = false) Date date, @DateTimeFormat(pattern = "yyyy") @RequestParam(required = false) Date year, @RequestParam(required = false) String near) {
        UsedRateResponse usedRateResponse = siteUsedCountService.getUsageRate(date, year, near);
        return instance(ResultCode.SUCCESS, usedRateResponse);
    }

    /**
     * @Description 历史使用率
     * @Param [date]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @ApiOperation(value = "历史使用率", notes = "历史使用率")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "siteName", value = "场地名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "开始日期", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", paramType = "query", dataType = "String")
    })
    @GetMapping("usageRateHistory")
    public ApiResult<PageInfo<CustomSiteUsedHistory>> getUsageRateHistory(@RequestParam(required = false, defaultValue = "1") int pageNum,
                                                                          @RequestParam(required = false, defaultValue = "10") int pageSize,
                                                                          @RequestParam(required = false) String siteName,
                                                                          @RequestParam(required = false) String startDate,
                                                                          @RequestParam(required = false) String endDate) {
        PageInfo<CustomSiteUsedHistory> siteList = siteUsedCountService.getUsageRateHistory(pageNum, pageSize, siteName, startDate, endDate);
        return instance(ResultCode.SUCCESS, siteList);
    }

    /**
     * @Description 列表
     * @Param [siteName, siteType, pageNum, pageSize]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("list")
    @ApiOperation(value = "场地列表", notes = "场地列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteName", value = "场地名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "siteType", value = "场地类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageSize", value = "页面显示条数", paramType = "query", dataType = "String")
    })
    public ApiResult<SiteListResponse> getSiteList(@RequestParam(required = false, defaultValue = "") String siteName, @RequestParam(required = false, defaultValue = "") String siteType, @RequestParam(required = false, defaultValue = "1") int pageNum,
                                                   @RequestParam(required = false, defaultValue = "10") int pageSize) {
        SiteListResponse siteListResponse = siteService.getSiteList(siteName, siteType, pageNum, pageSize);
        return instance(ResultCode.SUCCESS, siteListResponse);
    }

    /**
     * @Description 基本信息
     * @Param [siteCode, size]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("info")
    @ApiOperation(value = "场地基本信息", notes = "场地基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteCode", value = "场地Code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "size", value = "日期区间大小", paramType = "query", dataType = "int")
    })
    public ApiResult<SiteInfoResponse> getSiteInfo(@RequestParam(required = false) String siteCode,
                                                   @RequestParam(required = false, defaultValue = "8") int size) {
        SiteInfoResponse siteListResponse = siteService.getSiteInfo(siteCode, size);
        return instance(ResultCode.SUCCESS, siteListResponse);
    }

    /**
     * @Description 使用情况_年统计
     * @Param [siteCode]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("used/count")
    @ApiOperation(value = "场地使用情况年统计", notes = "场地使用情况年统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteCode", value = "场地code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份", paramType = "query", dataType = "Integer")
    })
    public ApiResult<SiteUsedCount> getSiteUsedCount(@RequestParam String siteCode, @RequestParam(required = false) Integer year) {
        String siteId = siteService.getSiteIdBySiteCode(siteCode);
        SiteUsedCount siteUsedCount = new SiteUsedCount();
        siteUsedCount.setSiteId(siteId);
        siteUsedCount.setYear(year);
        siteUsedCount.setMonth(0);
        siteUsedCount = siteUsedCountService.findOnResult(siteUsedCount);
        return instance(ResultCode.SUCCESS, siteUsedCount);
    }
    @GetMapping("getSiteUsedData")
    @ApiOperation(value = "场地使用情况统计", notes = "场地使用情况年统计")
    public ApiResult<SiteUsedDataVo> getSiteUsedData(@RequestParam String siteCode,
                                                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) Date startDate,
                                                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) Date endDate){
        SiteUsedDataVo siteUsedDataVo = siteService.getSiteUsedData(siteCode,startDate,endDate);
        return instance(ResultCode.SUCCESS, siteUsedDataVo);
    }


    /**
     * @Description 使用情况_月统计和详情
     * @Param [siteId, date]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("used")
    @ApiOperation(value = "场地使用情况", notes = "场地使用情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteCode", value = "场地Code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "date", value = "日期", paramType = "query", dataType = "Date")
    })
    public ApiResult<SiteUsedResponse> getSiteUsed(@RequestParam String siteCode, @DateTimeFormat(pattern = "yyyy-MM") @RequestParam(required = false) Date date) {
        String siteId = siteService.getSiteIdBySiteCode(siteCode);
        SiteUsedResponse siteUsedResponse = siteUsedCountService.getSiteUsed(siteId, date);
        return instance(ResultCode.SUCCESS, siteUsedResponse);
    }

    /**
     * @Description 使用情况_报警信息（根据上面传的bookingId)
     * @Param [bookingId]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("used/info")
    @ApiOperation(value = "场地出现报警时的详细信息", notes = "场地出现报警时的详细信息")
    @ApiImplicitParam(name = "bookingId", value = "预约id", paramType = "query", dataType = "String")
    public ApiResult<CustomSiteBooking> getUsedInfo(@RequestParam String bookingId) {
        CustomSiteBooking customSiteBooking = siteBookingService.getUsedInfo(bookingId);
        return instance(ResultCode.SUCCESS, customSiteBooking);
    }

    /**
     * @Description 监控记录
     * @Param [date, type, siteCode, pageNum, pageSize]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("monitoring/recordList")
    @ApiOperation(value = "场地监控记录", notes = "场地监控记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期", paramType = "query", dataType = "Date"),
            @ApiImplicitParam(name = "type", value = "报警类型", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "siteCode", value = "场地Code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", paramType = "query", dataType = "String")
    })
    public ApiResult<PageInfo<SiteAlerts>> getMonitoringRecordList(@DateTimeFormat(pattern = "yyyy-MM") @RequestParam(required = false) Date date,
                                                                   @RequestParam(required = false, defaultValue = "0") int type,
                                                                   @RequestParam String siteCode,
                                                                   @RequestParam(required = false, defaultValue = "1") int pageNum,
                                                                   @RequestParam(required = false, defaultValue = "10") int pageSize) {
        PageInfo<SiteAlerts> alertsPageInfo = siteAlertsService.getMonitoringRecordList(date, type, siteCode, pageNum, pageSize);
        return instance(ResultCode.SUCCESS, alertsPageInfo);
    }

    /**
     * @Description 监控记录_统计
     * @Param [type, size]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("monitoring/count")
    @ApiOperation(value = "场地月报警/故障统计", notes = "场地月报警/故障统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "报警类型", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "日期间隔", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "date", value = "日期", paramType = "query", dataType = "Date"),
            @ApiImplicitParam(name = "siteCode", value = "场地Code", paramType = "query", dataType = "String")
    })
    public ApiResult<MonitoringCountResponse> getMonitoringCount(@RequestParam(required = false, defaultValue = "0") int type, @RequestParam(required = false, defaultValue = "8") int size, @RequestParam String siteCode, @DateTimeFormat(pattern = "yyyy-MM") @RequestParam(required = false) Date date) {
        MonitoringCountResponse monitoringCountResponse = siteAlertsMonthService.getMonitoringCount(type, size, date, siteCode);
        return instance(ResultCode.SUCCESS, monitoringCountResponse);
    }

    /**
     * @Description 预约排期_概览
     * @Param [siteCode, date]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("booking/list")
    @ApiOperation(value = "场地预约排期", notes = "场地预约排期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteCode", value = "场地Code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "date", value = "日期", paramType = "query", dataType = "Date")
    })
    public ApiResult<BookingListResponse> getBookingList(@RequestParam String siteCode, @DateTimeFormat(pattern = "yyyy-MM") @RequestParam Date date) {
        BookingListResponse bookingListResponse = siteBookingService.getBookingList(siteCode, date);
        return instance(ResultCode.SUCCESS, bookingListResponse);
    }

    /**
     * @Description 预约排期_详情
     * @Param [bookingId]
     * @Return com.culturalCenter.dataCenter.Utils.ApiResult
     */
    @GetMapping("booking/info")
    @ApiOperation(value = "场地的详细信息", notes = "场地的详细信息")
    @ApiImplicitParam(name = "bookingId", value = "预约id", paramType = "query", dataType = "String")
    public ApiResult<CustomSiteBooking> getBookingInfo(@RequestParam String bookingId) {
        CustomSiteBooking customSiteBooking = siteBookingService.getUsedInfo(bookingId);
        return instance(ResultCode.SUCCESS, customSiteBooking);
    }

    /**
     * @Description 场地二维码（暂时无用）
     * @Param [requestVisitor]
     * @Return java.lang.String
     */
    @PostMapping("getQrCode")
    @ApiOperation(value = "获取场地二维码", notes = "获取场地二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "callerName", value = "访客姓名", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "callerSex", value = "访客性别", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "callerIdNo", value = "访客证件号", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "callerTel", value = "访客电话", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "loginTime", value = "开始时间(yyyy-xx-xx xx:xx)", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "planOutTime", value = "结束时间(yyyy-xx-xx xx:xx)", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "authorRegions", value = "场地编码(访问区域)", required = true, paramType = "body", dataType = "String")
    })
    public String getQrCode(@ApiIgnore @RequestBody RequestVisitorInfo requestVisitor) {
        try {
            requestVisitor.setEmpNo(empNo);
            requestVisitor.setEmpName(empName);
            requestVisitor.setDptName(dptName);
            requestVisitor.setCallReason(callReason);
            requestVisitor.setCallerCarInfo("");
            requestVisitor.setCallerPhoto("");
            requestVisitor.setCallerCorpName(callerCorpName);
            String s = DoorHttpUtil.sendRequestByVisitorInfo(visitorInfoUrl, key, requestVisitor);
            String code = JSON.parseObject(s).getString("code");
            if (!"0".equals(code)) {
                return JSONObject.toJSONString(instance(code, JSON.parseObject(s).getString("msg")), SerializerFeature.WriteMapNullValue);
            }
            RequestDoorTemplate template = new RequestDoorTemplate();
            template.setPageIndex("1");
            template.setPageSize("10");
            template.setStartTime(requestVisitor.getLoginTime() + ":00");
            template.setEndTime(requestVisitor.getPlanOutTime() + ":00");
            template.setEmpNo(requestVisitor.getEmpNo() != null ? requestVisitor.getEmpNo() : "");
            template.setCallerName(requestVisitor.getCallerName() != null ? requestVisitor.getCallerName() : "");
            template.setCallerIdNo(requestVisitor.getCallerIdNo() != null ? requestVisitor.getCallerIdNo() : "");
            String visitorInfo = DoorHttpUtil.sendRequestByTemplate(getVisitorInfoUrl, key, template);
            List<RequestVisitorInfo> requestVisitorInfos = JSON.parseArray(JSON.parseObject(JSON.parseObject(visitorInfo).getString("data")).getString("datalist"), RequestVisitorInfo.class);
            if (CollUtil.isNotEmpty(requestVisitorInfos)) {
                for (RequestVisitorInfo requestVisitorInfo : requestVisitorInfos) {
                    if (requestVisitor.getCallerIdNo().equals(requestVisitorInfo.getCallerIdNo())) {
                        return DoorHttpUtil.sendRequestToGetVisitorQrCode(visitorQrCodeUrl, key, requestVisitorInfo.getCallerId());
                    }
                }
            }
            return JSON.toJSONString(instance(ResultCode.FALL, "访客信息错误"));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            LogException.LogError(log, e);
            return JSON.toJSONString(instance(ResultCode.FALL));
        }
    }

}
